package com.unknowpupil.sell.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unknowpupil.sell.common.BasePage;
import com.unknowpupil.sell.common.enums.ErrorCodeEnum;
import com.unknowpupil.sell.domain.ProductInfo;
import com.unknowpupil.sell.dto.CartDTO;
import com.unknowpupil.sell.exception.SellException;
import com.unknowpupil.sell.mapper.ProductInfoMapper;
import com.unknowpupil.sell.service.IProductInfoService;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author AutoGenerator
 */
@Service
public class ProductInfoServiceImpl extends ServiceImpl<ProductInfoMapper, ProductInfo>implements IProductInfoService {

    @Override
    public IPage<ProductInfo> findProductInfoByType(BasePage page,Integer type) {
        LambdaQueryWrapper<ProductInfo> query = new LambdaQueryWrapper<>();
        query.eq(ProductInfo::getCategoryType,type);
        IPage<ProductInfo> result = baseMapper.selectPage(new Page<ProductInfo>(page.getCurrent(),page.getSize()),query);
        return result;
    }

    @Override
    @Transactional(rollbackFor = SellException.class)
    public void increaseStock(List<CartDTO> cartDTOList) {
        for(CartDTO cartDTO:cartDTOList) {
            ProductInfo productInfo = baseMapper.selectById(cartDTO.getProductId());
            if (productInfo == null) {
                throw new SellException(ErrorCodeEnum.PRODUCT_NOT_EXIST);
            }
            Integer result = productInfo.getProductStock()+cartDTO.getProductQuantity();
            productInfo.setProductStock(result);
            baseMapper.updateById(productInfo);
        }
    }

    @Override
    @Transactional(rollbackFor = SellException.class)
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for(CartDTO cartDTO:cartDTOList){
            ProductInfo productInfo = baseMapper.selectById(cartDTO.getProductId());
            if(productInfo==null){
                throw new SellException(ErrorCodeEnum.PRODUCT_NOT_EXIST);
            }
           Integer result = productInfo.getProductStock()-cartDTO.getProductQuantity();
            if(result<0){
                throw new SellException(ErrorCodeEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            baseMapper.updateById(productInfo);
        }
    }
}
